#include "widget.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QFileDialog>
#include <QMessageBox>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    QVBoxLayout *mainLayout = new QVBoxLayout();
    setLayout(mainLayout);

    QHBoxLayout *hBoxLayout = new QHBoxLayout();
    mainLayout->addLayout(hBoxLayout);

    hBoxLayout->addWidget(new QLabel("文件路径："));
    filePathLineEdit = new QLineEdit();
    hBoxLayout->addWidget(filePathLineEdit);

    QPushButton *pushButton;

    pushButton = new QPushButton("...");
    connect(pushButton, SIGNAL(clicked(bool)), this, SLOT(_selectFilePath()));
    hBoxLayout->addWidget(pushButton);

    hBoxLayout->addWidget(new QLabel("颜色类型："));
    colorTypeComboBox = new QComboBox();
    colorTypeComboBox->addItem("RGB24");
    hBoxLayout->addWidget(colorTypeComboBox);

    hBoxLayout->addWidget(new QLabel("图像宽度："));
    widthLineEdit = new QLineEdit("1280");
    widthLineEdit->setFixedWidth(100);
    hBoxLayout->addWidget(widthLineEdit);
    hBoxLayout->addWidget(new QLabel("图像高度："));
    heightLineEdit = new QLineEdit("720");
    heightLineEdit->setFixedWidth(100);
    hBoxLayout->addWidget(heightLineEdit);


    pushButton = new QPushButton("显示");
    connect(pushButton, SIGNAL(clicked(bool)), this, SLOT(_showImageFromFile()));
    hBoxLayout->addWidget(pushButton);

    imageLabel = new QLabel();
    mainLayout->addWidget(imageLabel);
}

Widget::~Widget()
{

}

void Widget::showErrorMessage(const QString &msg)
{
    QMessageBox::critical(this, "操作错误", msg);
}

void Widget::_selectFilePath()
{
    QString filePath = QFileDialog::getOpenFileName(this);
    if(filePath.isEmpty()) {
        return;
    }
    filePathLineEdit->setText(filePath);
}

void Widget::_showImageFromFile()
{
    bool ok;
    quint32 width, height;

    width = widthLineEdit->text().toUInt(&ok);
    if(!ok) {
        showErrorMessage("转换宽度数据错误！");
        return;
    }
    height = heightLineEdit->text().toUInt(&ok);
    if(!ok) {
        showErrorMessage("转换高度数据错误！");
        return;
    }
    QFile file(filePathLineEdit->text());
    if(!file.open(QIODevice::ReadOnly)) {
        showErrorMessage("打开图像文件失败！");
        return;
    }
    QByteArray data = file.read(width*height*3);
    QImage image(width, height, QImage::Format_RGB888);
    for(quint32 i=0; i<height; i++) {
        for(quint32 j=0; j<width; j++) {
            quint8 *rgb = (quint8 *)(data.data()+(i*width+j)*3);
            image.setPixelColor(j, i, qRgb(rgb[0], rgb[1], rgb[2]));
        }
    }

    imageLabel->setPixmap(QPixmap::fromImage(image));
}
